package com.ynet.middleground.contract.mq.consumer;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.stereotype.Component;

import com.ynet.core.exception.BusinessException;
import com.ynet.core.log.IfpLogger;
import com.ynet.core.util.IDUtil;
import com.ynet.middleground.contract.bean.UpdateTemplateStatusReq;
import com.ynet.middleground.contract.constant.TemplateStatusEnum;
import com.ynet.middleground.contract.model.TemplateModel;
import com.ynet.middleground.contract.mq.Sink;
import com.ynet.middleground.contract.utils.EnumUtil;

/**
 * @author liulx
 * @description 激活、停用模板消息订阅并处理
 * @date 2020-04-28 17:35
 */
@Component
public class UpdateTemplateConsumer {

    @Autowired
    TemplateModel templateModel;

    @StreamListener(Sink.I_CONTRACT)
    public void inputConsumer(Map<String, Object> msgMap) {
        IfpLogger.info("mq", "从Binding-{}收到信息-{}", Sink.I_CONTRACT, msgMap);
        String templateStatus = String.valueOf(msgMap.get("templateStatus"));
        Object channel = msgMap.get("channel");
        Object operationUserId = msgMap.get("operationUserId");
        Object templateIds = msgMap.get("templateIds");
        Object enterpriseIdObj = msgMap.get("enterpriseId");
        UpdateTemplateStatusReq req = new UpdateTemplateStatusReq();
        req.setTemplateIds((List<Integer>)templateIds);
        req.setTraceId(IDUtil.getSecureRandomId());
        req.setChannel(String.valueOf(channel));
        req.setOperationUserId((Integer)operationUserId);
        req.setRequestTime(new Date());
        if (enterpriseIdObj != null) {
            Integer enterpriseId;
            try {
                enterpriseId = Integer.valueOf(String.valueOf(enterpriseIdObj));
            } catch (NumberFormatException e) {
                enterpriseId = null;
            }
            req.setEnterpriseId(enterpriseId);
        }

        // 获取模板状态
        TemplateStatusEnum templateStatusEnum = EnumUtil.getEnumObject(TemplateStatusEnum.class,
            e -> e.getCode().equals(templateStatus), "模板参数类型参数值错误", "ECCT0108");
        switch (templateStatusEnum) {
            case ACTIVATING:
                templateModel.activingTemplate(req);
                break;
            case ACTIVATED:
                templateModel.activeTemplate(req);
                break;
            case DISABLED:
                templateModel.disableTemplate(req);
                break;
            default:
                throw new BusinessException("模板状态参数值错误", "ECCT0108");
        }
    }

}
